package com.bridgeintelligent.tag.scene.service;

import com.bridgeintelligent.tag.remotefile.RemoteFileHandler;
import com.bridgeintelligent.tag.scene.api.IUploadService;
import com.bridgeintelligent.tag.scene.api.entity.ImgFile;
import com.bridgeintelligent.tag.scene.mapper.ImgFileMapper;
import com.bridgeintelligent.tag.user.mgmt.pojo.User;
import com.bridgeintelligent.tag.webserver.dim.mgmt.api.IdWorker;
import com.bridgeintelligent.tag.webserver.security.TagSecurityHelper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Date;

/**
 * @description
 * @author: grp 2021-01-12 14:41
 **/
@Service
@Slf4j
@AllArgsConstructor
public class UploadServiceImpl implements IUploadService {

    private ImgFileMapper imgFileMapper;
    private RemoteFileHandler remoteFileHandler;

    private final static String PATH_PRE_FORMAT = "/images/%s";
    @Override
    public String upload(MultipartFile img) {
        ImgFile imgFile = new ImgFile();
        String[] split = img.getOriginalFilename().split("\\.");
        User user = TagSecurityHelper.currentUser();
        imgFile.setCreateTime(new Date()).setCreatorId(user.getUserId()).setId(IdWorker.nextId())
                .setName(img.getOriginalFilename())
                .setType(split[1]);
        String imgName = imgFile.getId()+ "." +imgFile.getType();
        String path = remoteFileHandler.writeByPath(img,
                remoteFileHandler.getPath(String.format(PATH_PRE_FORMAT,
                        DateFormatUtils.format(new Date(), DateFormatUtils.ISO_8601_EXTENDED_DATE_FORMAT.getPattern()
        ))),imgName);
        imgFile.setPath(path).setContentType(img.getContentType());
        imgFileMapper.insert(imgFile);
        return imgName;
    }

    @Override
    public void download(String id, HttpServletRequest request, HttpServletResponse response) {
        ImgFile imgFile = imgFileMapper.findImgFile(id);
        if(imgFile==null){
            response.setStatus(HttpStatus.NOT_FOUND.value());
            return;
        }
        File file = new File(imgFile.getPath());
        if(!file.exists()){
            response.setStatus(HttpStatus.NOT_FOUND.value());
            return;
        }
        byte[] buff = new byte[1024];
        try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            ServletOutputStream outputStream = response.getOutputStream()) {
            while (bis.read(buff) != -1) {
                outputStream.write(buff, 0, buff.length);
                outputStream.flush();
            }
            IOUtils.closeQuietly(outputStream);
            IOUtils.closeQuietly(bis);
        }catch (Exception e){
            log.error("获取图片失败",e);
        }
    }
}
